package cn.rongdao.jrkabao.ui.loan;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.util.ArrayMap;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.ui.activity.FRStartActivity;
import com.mifengkong.frtools.ui.statusbar.FRStatusBar;
import com.mifengkong.frtools.util.FRDisplayMetrics;
import com.mifengkong.frtools.util.FRLog;
import com.mifengkong.frtools.util.FRToast;
import com.mifengkong.frwidget.titlebar.TitleBarUIComponent;
import com.mifengkong.statistic.talkingdata.TalkingData;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import cn.rongdao.jrkabao.App;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.base.FRBaseLooperRequestActivity;
import cn.rongdao.jrkabao.bean.information.apply.ApplyInfoBean;
import cn.rongdao.jrkabao.bean.information.apply.OrderResultBean;
import cn.rongdao.jrkabao.bean.loan.CreditCardLoansDateBean;
import cn.rongdao.jrkabao.constant.InfoConstant;
import cn.rongdao.jrkabao.dao.UserDao;
import cn.rongdao.jrkabao.model.information.apply.GetApplyNeedInfoModel;
import cn.rongdao.jrkabao.model.information.apply.LoanApplyModel;
import cn.rongdao.jrkabao.model.loan.CreditCardLoansModel;
import cn.rongdao.jrkabao.model.loan.CreditCardLoansRepaymentModel;
import cn.rongdao.jrkabao.ui.IdentificationVerificate.IdentificationWithValidationItem.status.StatusForNonCompliantActivity;
import cn.rongdao.jrkabao.ui.information.MyOwnLoanIncreaseAmountActivity;
import cn.rongdao.jrkabao.ui.information.adapter.baseadapter.BaseRecycleAdapter;
import cn.rongdao.jrkabao.ui.loan.adapter.CreditLoanMaterialAdapter;
import cn.rongdao.jrkabao.ui.loan.adapter.CreditLoanTabAdapter;
import cn.rongdao.jrkabao.ui.loan.success.ApplySuccessActivity;
import cn.rongdao.jrkabao.ui.loan.uicomponent.LoanCommitNextButtonUIComponent;
import cn.rongdao.jrkabao.ui.loan.uicomponent.LoanCommitSmallQuotaComponent;
import cn.rongdao.jrkabao.ui.webview.WebViewActivity;
import cn.rongdao.jrkabao.util.CreditCardLoansAnimaManager;
import cn.rongdao.jrkabao.util.NumberUtil;
import cn.rongdao.jrkabao.widget.CustomSeekBar;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/*
* Created by Wang on 17/9/20.
* 速贷信用卡贷界面
* */
public class LoanCommitActivity extends FRBaseLooperRequestActivity {
    public static final String FROM_DATE = "date";
    public static final String FROM_TERM = "term";
    public static final String FROM_RMB = "rmb";
    public static final String FROM_JINE = "jine";


    @BindView(R.id.credit_cardloans_titlebar)
    TitleBarUIComponent titleBarUIComponent;
    @BindView(R.id.credit_cardloans_recyclerView)
    RecyclerView recyclerViewTab;                //期限选择列表
    @BindView(R.id.credit_cardloans_material)
    LinearLayout materialLayout;               //材料展示容器
    @BindView(R.id.credit_cardloans_material_rcl)
    RecyclerView material_Recycle;              //材料展示列表
    @BindView(R.id.copy_textview)
    TextView mCopyTextview;                      //再父布局里面复制的View
    @BindView(R.id.parent_container)
    RelativeLayout parent_container;              //父布局的id
    @BindView(R.id.credit_cardloans_term)
    TextView termText;                             //"期限"字样
    @BindView(R.id.credit_cardloans_amount_tv)
    TextView mLoansAmount;                         //可贷的金额
    @BindView(R.id.credit_cardloans_seekBar)
    CustomSeekBar seekBar;                               //滑动块
    @BindView(R.id.credit_cardloans_amount_jine)
    TextView mSeekBarJine;                         //滑块下面的金额
    @BindView(R.id.credit_cardloans_amount_min)
    TextView mAmountMin;                           //seekbar左边显示的最小值
    @BindView(R.id.credit_cardloans_amount_max)
    TextView mAmountMax;                           //seekbar右边显示的最大值
    @BindView(R.id.img_dowm)
    ImageView mImgDowm;                            //动画执行后显示的图标
    @BindView(R.id.bg_view)
    View bg_view;                                  //渐变背景图
    @BindView(R.id.credit_cardloans_refound)
    TextView refound;                              //预估每月还款字样
    @BindView(R.id.credit_cardloans_refound_amount)
    TextView mRefoundAmount;                        //预估每月还款金额
    @BindView(R.id.credit_cardloans_netButton)
    LoanCommitNextButtonUIComponent nextButtonUIComponent; //点击下一步按钮
    @BindView(R.id.credit_cardloans_upQuota)
    ImageView mUpQuotaImg;             //提额
    @BindView(R.id.recycler_container)
    LinearLayout recycler_container;    //包裹在RecyclerView外面的一层父布局
    @BindView(R.id.lca_remind)
    ImageView remindIv;    //提示信息


    private CreditLoanTabAdapter loanTabAdapter;
    private CreditLoanMaterialAdapter materialAdapter;
    private List<CreditCardLoansDateBean.StagesBean> allData;
    protected Map<String, String> orderParmasMap = new ArrayMap<>();
    private int[] location;
    private int[] locationTerm;
    private int[] locationAmount;
    private int[] locationJine;
    private boolean isOpen = false;
    private GridLayoutManager gridLayoutManager;
    private float screenWidthPixels;
    private float screenHeightPixels;
    private int originalHeight = 0;
    private int bgViewOriginHeight = 0;
    private int targetHeight = 0;
    private int dp_37;
    private int dp_40;
    private int dp_220;
    private String mProductId;    //产品ID
    private int pointMeUp = -2; //是否显示提额
    private CreditCardLoansAnimaManager cardLoansAnimaManager;//动画管理的类
    private Disposable mDisposable;
    private int mCheckType = -2;    //
    private String mCateId;
    private String loanName;
    private ApplyInfoBean.FirstItemBean mFirstItemBean = null;
    private String source = InfoConstant.PAGE_SOURCE_DEFAULT;//是否是从多推列表进来的   是  1   否  0
    private Map<String, String> commitParmasMap = new ArrayMap(); //提交的参数
    private Map<String, String> mGioMap = new ArrayMap();   //埋点的参数
    //    private AlertDialog alertDialog; //米粒贷弹窗
    private GridLayoutManager tabGridLayoutManager;
    private boolean isExecution = false;

    ViewTreeObserver.OnGlobalLayoutListener mOnGlobalLayoutListener;
    private String mIndexSource;//是否是从首页进来的   是  1   否  0
    private View mPopupWindowView;
    private TextView mPopupTextview;
    private String mExclamation;
    private LoanCommitSmallQuotaComponent smallQuotaComponent;
    private int selectedSmallQu0ta = -1;  //是否勾选小额贷
    private String mExclamationUrl;

    public static void start(Context context, String cate_id, String product_id, String loanName) {
        Bundle bundle = new Bundle();
        bundle.putString(InfoConstant.PRODUCT_ID, product_id);
        bundle.putString(InfoConstant.CATE_ID, cate_id);
        bundle.putString(InfoConstant.LOAN_NAME, loanName);
        bundle.putString(InfoConstant.INDEX_SOURCE, "1");
        FRStartActivity.start(context, LoanCommitActivity.class, bundle);
    }

    /**
     * 不是从首页进来的，比如说是到账单或者公积金回跳到这里的
     *
     * @param context
     * @param cate_id
     * @param product_id
     * @param source
     * @param loanName
     */
    public static void startWithOtherJump(Context context, String cate_id, String product_id, String source, String loanName) {
        Bundle bundle = new Bundle();
        bundle.putString(InfoConstant.PAGE_SOURCE, source);
        bundle.putString(InfoConstant.PRODUCT_ID, product_id);
        bundle.putString(InfoConstant.CATE_ID, cate_id);
        bundle.putString(InfoConstant.LOAN_NAME, loanName);
        bundle.putString(InfoConstant.INDEX_SOURCE, "0");
        FRStartActivity.start(context, LoanCommitActivity.class, bundle);
    }

    @Override
    protected int layoutRes() {
        return R.layout.activity_loan_commit;
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        //here we can use getIntent() to get the extra data.
        getData();
        titleBarUIComponent.initTitle(loanName);
        isExecution = false;
    }

    @Override
    protected void initView() {
        super.initView();
        FRStatusBar.setTranslucentForImageView(this, findViewById(R.id.root_view));
        dp_37 = FRDisplayMetrics.dp2px(App.getInstance(), 37);
        dp_40 = FRDisplayMetrics.dp2px(App.getInstance(), 40);
        dp_220 = FRDisplayMetrics.dp2px(LoanCommitActivity.this, 242);

        screenWidthPixels = getResources().getDisplayMetrics().widthPixels;
        screenHeightPixels = getResources().getDisplayMetrics().heightPixels;


        initTermTextMarginTop();
        if (cardLoansAnimaManager == null) {
            cardLoansAnimaManager = new CreditCardLoansAnimaManager();
        }

        smallQuotaComponent = (LoanCommitSmallQuotaComponent) findViewById(R.id.credit_cardloans_smallquota);
        nextButtonUIComponent.setBgAndTextColorForLoan();
        mRefoundAmount.setText("请选择还款期限");
        initTabRecyclerView();
        initAnimaManager();
        initListener();
        initCommitParams();
        getData();
        initTitle();
    }


    /*代码设置布局的高度*/
    private void initTermTextMarginTop() {
        //期限的位置
        RelativeLayout.LayoutParams lps = new RelativeLayout.LayoutParams(FRDisplayMetrics.dp2px(this, 188), ViewGroup.LayoutParams.WRAP_CONTENT);
        lps.topMargin = (int) (screenHeightPixels * 0.53);
        lps.addRule(RelativeLayout.CENTER_HORIZONTAL);
        lps.width = (int) (screenWidthPixels / 2);
        termText.setLayoutParams(lps);
        //图标的位置
        RelativeLayout.LayoutParams lps1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lps1.topMargin = (int) (screenHeightPixels * 0.19);
        lps1.addRule(RelativeLayout.CENTER_HORIZONTAL);
        mImgDowm.setLayoutParams(lps1);
        //提额布局
        RelativeLayout.LayoutParams lps2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lps2.topMargin = (int) (screenHeightPixels * 0.5);
        lps2.addRule(RelativeLayout.ALIGN_PARENT_END);
        mUpQuotaImg.setLayoutParams(lps2);
        //金额数字
        ViewGroup.LayoutParams layoutParams = mLoansAmount.getLayoutParams();
        layoutParams.width = (int) (screenWidthPixels / 2);
        mLoansAmount.setLayoutParams(layoutParams);
        //金额字样
        ViewGroup.LayoutParams layoutParams1 = mSeekBarJine.getLayoutParams();
        layoutParams1.width = (int) screenWidthPixels / 2;
        mSeekBarJine.setLayoutParams(layoutParams1);
    }

    @Override
    public String getCateId() {
        return mCateId;
    }

    @Override
    public String getLoanName() {
        return loanName;
    }

    @Override
    protected ApplyInfoBean.FirstItemBean getUserFirstFillInItem() {
        return mFirstItemBean;
    }

    @Override
    protected String getProductId() {
        return mProductId;
    }

    @Override
    protected String getPageSource() {
        return source;
    }

    private void initTabRecyclerView() {
        //期限选择RecyclerView
        tabGridLayoutManager = new GridLayoutManager(this, 3);
        recyclerViewTab.setLayoutManager(tabGridLayoutManager);
        loanTabAdapter = new CreditLoanTabAdapter(this);
        loanTabAdapter.setCopy_view(mCopyTextview);
        recyclerViewTab.setAdapter(loanTabAdapter);
        //资料完善RecyclerView
        gridLayoutManager = new GridLayoutManager(this, CreditLoanMaterialAdapter.SPAN_COUNT_OTHER);
        material_Recycle.setLayoutManager(gridLayoutManager);
        materialAdapter = new CreditLoanMaterialAdapter(this, gridLayoutManager);
        material_Recycle.setAdapter(materialAdapter);
    }

    /*设置动画执行需要的数据*/
    private void initAnimaManager() {
        if (cardLoansAnimaManager == null) {
            cardLoansAnimaManager = new CreditCardLoansAnimaManager();
        }
        cardLoansAnimaManager.setBg_view(bg_view);
        cardLoansAnimaManager.setAmount_max(mAmountMax);
        cardLoansAnimaManager.setAmount_min(mAmountMin);
        cardLoansAnimaManager.setCopy_textview(mCopyTextview);
        cardLoansAnimaManager.setGridLayoutManager(gridLayoutManager);
        cardLoansAnimaManager.setImg_dowm(mImgDowm);
        cardLoansAnimaManager.setLoans_amount(mLoansAmount);
        cardLoansAnimaManager.setMaterialAdapter(materialAdapter);
        cardLoansAnimaManager.setRecyclerViewTab(recyclerViewTab);
        cardLoansAnimaManager.setSeekBar(seekBar);
        cardLoansAnimaManager.setMaterialLayout(materialLayout);
        cardLoansAnimaManager.setTermText(termText);
        cardLoansAnimaManager.setCusLinearLayout(recycler_container);
    }

    /*获取页面数据*/
    private void getData() {
        getIntentData();
        if (TextUtils.isEmpty(mCateId)) {
            return;
        }
        if (TextUtils.isEmpty(mProductId)) {
            return;
        }
        getLoanData();
    }

    private void getLoanData() {
        //获取期限列表 seekBar的数据
        CreditCardLoansModel.getInstance().execute(source, mProductId, mIndexSource,
                new FRBaseObserver<CreditCardLoansDateBean>(this, "正在加载,请稍候...") {
                    @Override
                    protected void onBaseNext(CreditCardLoansDateBean data) {
                        if (data != null) {

                            initSmallQuotaData(data);

                            List<CreditCardLoansDateBean.StagesBean> stages = data.getStages();
                            if (stages != null && stages.size() > 0) {
                                allData = stages;
                                pointMeUp = data.getPointMeUp();
                            }
                            //是否显示提额的标志
                            if (1 == pointMeUp) {
                                mUpQuotaImg.setVisibility(View.VISIBLE);
                            } else {
                                mUpQuotaImg.setVisibility(View.INVISIBLE);
                            }
//                            //是否显示弹窗
//                            if (1 == data.getPopupHint()) {
//                                //弹窗的出现
//                                initMiLiDaiDialog();
//                            }
                            //没有产品了
                            if (productIsEmpty(data)) return;
                            nextButtonUIComponent.setNextButtonContent(String.valueOf(data.getToday_leave()), "立即申请");

                            mCateId = data.getCate_id();
                            mProductId = data.getProduct_id();
                            getMaterialData();
                            initSeekBar(data);

                            setRepaymentDesc();
                            mExclamationUrl = data.getExclamation_url();
                            mExclamation = data.getExclamation();
                        }
                    }
                });
    }

    //大额贷款里面的小额贷数据
    private void initSmallQuotaData(CreditCardLoansDateBean data) {
        String petty_loan_exits = data.getPetty_loan_exits();
        //如果petty_loan_exits字段为空的话就不显示,如果为0的话也不显示
        if (TextUtils.isEmpty(petty_loan_exits)) {
            smallQuotaComponent.setOwnVisible(false);
            selectedSmallQu0ta = -1;
        } else {
            if ("0".endsWith(petty_loan_exits)) {
                smallQuotaComponent.setOwnVisible(false);
                selectedSmallQu0ta = -1;
            } else {
                selectedSmallQu0ta = 1;
                smallQuotaComponent.setOwnVisible(true);
                CreditCardLoansDateBean.PettyLoanBean petty_loan = data.getPetty_loan();
                if (petty_loan == null) {
                    return;
                }
                CreditCardLoansDateBean.PettyLoanBean.PeriodBean period = petty_loan.getPeriod();
                String desc = period.getDesc();
                smallQuotaComponent.setSmallquoteMoney(petty_loan.getAmount());
                smallQuotaComponent.setSmallquoteDay(desc);
            }
        }
    }

    private boolean productIsEmpty(CreditCardLoansDateBean data) {
        if (data.getCode() == InfoConstant.VERIFY_STATUS_DEFAIL) {
            finish();
            StatusForNonCompliantActivity.start(getActivity(), mCateId, String.valueOf(InfoConstant.VERIFY_STATUS_DEFAIL), source);
            return true;
        }
        return false;
    }

    private void setRepaymentDesc() {
        if (InfoConstant.PETTY_LOAN_CATE_ID.equals(mCateId)) {
            refound.setText("预估还款");
        } else {
            refound.setText("预估每月还款");
        }
    }

    private void getIntentData() {
        source = getIntent().getStringExtra(InfoConstant.PAGE_SOURCE);
        if (TextUtils.isEmpty(source)) {
            source = InfoConstant.PAGE_SOURCE_DEFAULT;
        }
        mProductId = getIntent().getStringExtra(InfoConstant.PRODUCT_ID);
        mCateId = getIntent().getStringExtra(InfoConstant.CATE_ID);
        loanName = getIntent().getStringExtra(InfoConstant.LOAN_NAME);
        mIndexSource = getIntent().getStringExtra(InfoConstant.INDEX_SOURCE);
        if (TextUtils.isEmpty(mIndexSource)) {
            mIndexSource = "1";
        }
    }

//    /*米拉贷弹窗*/
//    private void initMiLiDaiDialog() {
//        if (alertDialog == null) {
//            alertDialog = new AlertDialog.Builder(this).setContentView(R.layout.dialog_not_find_mail).setOnClickListener(R.id.dialog_miladai_sure, new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    alertDialog.dismiss();
//                }
//            }).fullWidth().setWidthAndHeight(FRDisplayMetrics.dp2px(this, 290), FRDisplayMetrics.dp2px(this, 173)).create();
//        }
//        alertDialog.setCanceledOnTouchOutside(false);
//        alertDialog.show();
//        alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
//            @Override
//            public void onDismiss(DialogInterface dialog) {
//                finish();
//            }
//        });
//    }

    /*获取完善资料的数据*/
    private void getMaterialData() {
        orderParmasMap.put("show_module", "must");
        orderParmasMap.put("product_id", mProductId);
        //获取完善资料的列表
        //(this, isFirstRequest ? "正在加载" : null)
        GetApplyNeedInfoModel.getInstance().execute(orderParmasMap, new FRBaseObserver<ApplyInfoBean>(this) {

            @Override
            protected void onBaseNext(ApplyInfoBean data) {
                if (data != null) {
                    mFirstItemBean = data.getFirst_item();
                    mCheckType = data.getCheck_type();
                    if (mCheckType == -1) {
                        if (!mIsRunning) {
                            startRun();
                        }
                    } else {
                        stopRunning();
                    }
                    materialAdapter.setData(data.getMust_list(), true);

                }
            }

        });

    }

    //获取再某个分期范围内每月要还的数值的数据
    private void getStaging(String amount, String product_id, String stages) {
        CreditCardLoansRepaymentModel.getInstance().execute(amount, product_id, stages, new FRBaseObserver<String>(this) {
            @Override
            protected void onBaseNext(String data) {
                mRefoundAmount.setText(data);
            }
        });
    }

    /*设置seekBar的数据*/
    private void initSeekBar(CreditCardLoansDateBean data) {
        int high = data.getHigh() / 100;
        int rela_high = high * 100;
        int lowest = data.getLowest();
        int offset = data.getOffset();
        int default_money = data.getDefault_money();
        if (default_money > data.getHigh()) {
            default_money = data.getHigh();
        }
        if (default_money < lowest) {
            default_money = lowest;
        }
        mAmountMax.setText(String.valueOf(rela_high));
        mAmountMin.setText(String.valueOf(lowest));
        mLoansAmount.setText(NumberUtil.splitNum(default_money));
        //判断有无初始值
        if (default_money > 0) {
            seekBar.init(String.valueOf(lowest), String.valueOf(rela_high), String.valueOf(offset), String.valueOf(default_money));
        } else {
            seekBar.init(String.valueOf(lowest), String.valueOf(rela_high), String.valueOf(offset), String.valueOf(lowest));
        }
        if (default_money > 0) {
            initTimeLimit(default_money);
        }
       /* if (itemSelectedBean != null) {
            getStaging(String.valueOf(default_money), mProductId, itemSelectedBean.getVal());
        }*/
    }

    /*期限列表设置数据*/
    private void initTimeLimit(int money) {
        boolean haveData = false;
        if (allData != null) {
            for (int i = 0; i < allData.size(); i++) {
                CreditCardLoansDateBean.StagesBean stagesBean = allData.get(i);
                int min_money = stagesBean.getMin_money();
                int max_money = stagesBean.getMax_money();
                if (money >= min_money && money < max_money) {
                    if (loanTabAdapter.getMaxValue() == max_money) {
                        return;
                    }
                    List<CreditCardLoansDateBean.StagesBean.PeriodBean> period = stagesBean.getPeriod();
                    if (period != null && period.size() > 0) {
                        loanTabAdapter.setRefreshData(period);
                        loanTabAdapter.setMaxValue(max_money);
                        location = null;
                        //默认选中第一个
                        String lastSelectedItem = loanTabAdapter.getLastSelectedItem();
                        if (TextUtils.isEmpty(lastSelectedItem)) {
                            mOnGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
                                @Override
                                public void onGlobalLayout() {
                                    View mChildAt = tabGridLayoutManager.getChildAt(0);
                                    if (mChildAt != null) {
                                        TextView view = (TextView) mChildAt.findViewById(R.id.item_creditcard_tv);
                                        getItemLocation(view);
                                        recyclerViewTab.getViewTreeObserver().removeGlobalOnLayoutListener(mOnGlobalLayoutListener);
                                    }
                                }
                            };
                            recyclerViewTab.getViewTreeObserver().addOnGlobalLayoutListener(mOnGlobalLayoutListener);
                            loanTabAdapter.setItemTage(0);
                        } else {
                            for (int j = 0; j < period.size(); j++) {
                                String val = period.get(j).getVal();
                                if (lastSelectedItem.equals(val)) {
                                    haveData = true;
                                    View view = loanTabAdapter.setItemTage(j);
                                    if (view != null) {
                                        getItemLocation(view);
                                    }
                                    break;
                                }
                            }
                            if (!haveData) {
                                loanTabAdapter.setItemTage(0);
                            }

                        }
                    }
                    break;
                }
            }
        }
    }

    /*初始化title数据*/
    private void initTitle() {
        //返回键
        titleBarUIComponent.initLeftBack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //标题
        titleBarUIComponent.initTitle(loanName);
        //右边客服
        titleBarUIComponent.initRightTvServiceWhite(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //title右边点击客服的头像\
                startHelpCenter();
            }
        });

    }

    /*设置各种的点击事件*/
    private void initListener() {

        //提额按钮
        mUpQuotaImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyOwnLoanIncreaseAmountActivity.start(LoanCommitActivity.this, mCateId, mProductId);

            }
        });
        //点击日期选择期限
        loanTabAdapter.setOnItemClickListener(R.id.item_creditcard_tv, new BaseRecycleAdapter.ItemClickListener() {
            @Override
            public void onItemClicked(View view, int position) {
                loanTabAdapter.setItemTage(position);
                CreditCardLoansDateBean.StagesBean.PeriodBean itemDataBean = loanTabAdapter.getItemDataBean(position);
                if (itemDataBean != null) {
                    final String amount = mLoansAmount.getText().toString().trim().replace(",", "");
                    final String val = itemDataBean.getVal();
                    seekbarProgressChangeFilterDataByTime(position, new Consumer<Integer>() {
                        @Override
                        public void accept(@NonNull Integer integer) throws Exception {
                            getStaging(amount, mProductId, val);
                        }
                    });
                }
                getItemLocation(view);

            }
        });
        //展示材料的布局点击展开
        materialLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                runAnima();
            }
        });
        //顶部设置复原动画
        bg_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (gridLayoutManager.getSpanCount() == CreditLoanMaterialAdapter.SPAN_COUNT_ONE) {
                    runAnima();
                }
            }
        });
        //确认提交按钮
        nextButtonUIComponent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean needOpen = false;//是否需要动画打开给用户看所有的资料
                needOpen = mCheckType != 1 ? true : false;
                if (needOpen && gridLayoutManager.getSpanCount() != CreditLoanMaterialAdapter.SPAN_COUNT_ONE) {
                    runAnima();
                    return;
                } else {
                    //选择的贷款金额
                    String loansAmount = mLoansAmount.getText().toString().trim().replace(",", "");
                    if (mCheckType != 1) {
                        FRToast.showToastSafe("请先完善资料!");
                        return;
                    }
                    if (TextUtils.isEmpty(loansAmount) && Integer.parseInt(loansAmount) <= 0) {
                        FRToast.showToastSafe("请选择贷款金额!");
                        return;
                    }

                    CreditCardLoansDateBean.StagesBean.PeriodBean itemSelectedStatus = loanTabAdapter.getItemSelectedBean();
                    if (null == itemSelectedStatus) {
                        FRToast.showToastSafe("请选择贷款期限!");
                        return;
                    }
                    commit();

                }

            }
        });

        materialAdapter.setOnItemActionListener(listener);
        //seekBar的滑动监听
        seekBar.setMeOnSeekBarChangeListener(new CustomSeekBar.MeOnSeekBarChangeListener() {
            @Override
            public void meOnProgressChanged(SeekBar seekBar1, int progress, boolean b, final int currentNumber) {
                mLoansAmount.setText(NumberUtil.splitNum(currentNumber));
                mRefoundAmount.setText("请选择还款期限");
                CreditCardLoansDateBean.StagesBean.PeriodBean itemSelectedBean = loanTabAdapter.getItemSelectedBean();
                if (itemSelectedBean != null) {
                    final String amount = mLoansAmount.getText().toString().trim().replace(",", "");
                    final String val = itemSelectedBean.getVal();
                    seekbarProgressChangeFilterDataByTime(1, new Consumer<Integer>() {
                        @Override
                        public void accept(@NonNull Integer integer) {
                            getStaging(amount, mProductId, val);
                            initTimeLimit(currentNumber);
                        }
                    });
                }
            }
        });
    }

    /*设置*/
    private void initCommitParams() {
        commitParmasMap.put("source", source);

        mGioMap.put("product_name", loanName);
        mGioMap.put("product_type", mCateId);
    }

    /*提交按钮*/
    private void commit() {
        final CreditCardLoansDateBean.StagesBean.PeriodBean itemSelectedStatus = loanTabAdapter.getItemSelectedBean();
        if (itemSelectedStatus == null) {
            return;
        }
        String val = itemSelectedStatus.getVal();
        commitParmasMap.put("product_id", mProductId);
        commitParmasMap.put("amount", mLoansAmount.getText().toString().replace(",", ""));
        commitParmasMap.put("stages", val);
        //是否显示小额贷
        if (selectedSmallQu0ta == 1) {
            boolean clickState = smallQuotaComponent.getClickState();
            //是否勾选要小额贷
            if (clickState) {
                //勾选了小额贷
                commitParmasMap.put("is_choose_xiaoedai", "1");
            } else {
                //没勾选
                commitParmasMap.put("is_choose_xiaoedai", "0");
            }
        } else if (selectedSmallQu0ta == -1) {
            //没显示小额贷
            commitParmasMap.put("is_choose_xiaoedai", "0");
        }
        LoanApplyModel.getInstance().execute(commitParmasMap, new FRBaseObserver<OrderResultBean>(this, "正在提交...") {
            @Override
            protected void onBaseNext(OrderResultBean data) {
                try {
                    TalkingData.applySuccess(UserDao.getInstance().getPhone(), data.getOrder_id().get(0), mLoansAmount.getText().toString().replace(",", ""), itemSelectedStatus.getDesc(), mProductId);
                } catch (Exception e) {

                }
                ApplySuccessActivity.start(getActivity(), mCateId, data.getOrder_id().get(0));
            }
        });

    }

    /*开启每个控件的动画*/
    private void runAnima() {
        materialLayout.setEnabled(false);
        bg_view.setEnabled(false);
        recycler_container.setEnabled(false);

        //移动后的位置
        int x = (int) (screenWidthPixels / 2);
        int xx = (int) (screenWidthPixels * 0.14);
        int dateY = (int) (screenHeightPixels * 0.14);
        if (locationTerm == null) {
            locationTerm = new int[2];

            termText.getLocationOnScreen(locationTerm);
        }
        if (locationAmount == null) {
            locationAmount = new int[2];
            mLoansAmount.getLocationOnScreen(locationAmount);
        }
        if (locationJine == null) {
            locationJine = new int[2];
            mSeekBarJine.getLocationOnScreen(locationJine);
        }
        if (targetHeight == 0) {
            originalHeight = materialLayout.getMeasuredHeight();
            //是否有小额贷那个选项
            if (selectedSmallQu0ta == 1) {
                targetHeight = (int) (screenHeightPixels * 0.313) + originalHeight;
            } else {
                targetHeight = (int) (screenHeightPixels * 0.392) + originalHeight;
            }
        }
        if (bgViewOriginHeight == 0) {
            bgViewOriginHeight = bg_view.getMeasuredHeight() + dp_40;

        }
        //"金额"字样
        cardLoansAnimaManager.tran(isOpen, FROM_JINE, mSeekBarJine, locationJine, 0, dateY + dp_40);
        //金额数量
        cardLoansAnimaManager.tran(isOpen, FROM_RMB, mLoansAmount, locationAmount, 0, dateY);
        if (location != null) {
            //"期限"字样
            cardLoansAnimaManager.tran(isOpen, FROM_TERM, termText, locationTerm, x, dateY + dp_37);
            //日期
            cardLoansAnimaManager.tran(isOpen, FROM_DATE, mCopyTextview, location, x + xx, dateY);
        } else {
            termText.setVisibility(View.GONE);
        }
        //透明度的动画
       /* cardLoansAnimaManager.bgViewAlphaAnim2(isOpen);*/
        //列表展开
        switchLayout();
        //渐变背景动画
        cardLoansAnimaManager.bgViewAnim2(isOpen, bgViewOriginHeight, dp_220);
        if (!isOpen) {
            if (1 == pointMeUp) {
                mUpQuotaImg.setVisibility(View.GONE);
            }
        } else {
            if (1 == pointMeUp) {
                mUpQuotaImg.setVisibility(View.VISIBLE);
            }
        }
        isOpen = !isOpen;
    }

    /*获取点击期限列表的item的X Y 坐标*/
    private void getItemLocation(View view) {
        if (location == null) {
            location = new int[2];
        }
        TextView view1 = (TextView) view;
        String s = view1.getText().toString();
        int[] parentLocation = new int[2];
        view.getLocationOnScreen(location);
        parent_container.getLocationOnScreen(parentLocation);     //获取父View相对屏幕位置
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mCopyTextview.getLayoutParams();
        params.leftMargin = location[0] - parentLocation[0];
        params.topMargin = location[1] - parentLocation[1];
        // params.width = (int) (screenWidthPixels *0.31);
        mCopyTextview.setLayoutParams(params);
        // mCopyTextview.setText(s);
    }

    /*资料列表高度增加动画*/
    private void switchLayout() {
        if (gridLayoutManager.getSpanCount() != CreditLoanMaterialAdapter.SPAN_COUNT_ONE) {
            cardLoansAnimaManager.performAnim2(false, targetHeight, originalHeight);
        } else {
            cardLoansAnimaManager.performAnim2(true, targetHeight, originalHeight);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isExecution) {
            getMaterialData();
        }
        isExecution = true;
    }

    /**
     * 根据时间过滤重复数据
     *
     * @param t
     * @param consumer
     * @param <T>
     */
    protected <T> void seekbarProgressChangeFilterDataByTime(final T t, Consumer consumer) {
        //交给RxJava去做
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
        mDisposable = Observable.create(new ObservableOnSubscribe<T>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<T> e) throws Exception {
                e.onNext(t);
            }
        }).debounce(500, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                .subscribe(consumer);
    }

    @Override
    protected void baseLooperMethod() {
        super.baseLooperMethod();
        getMaterialData();
    }

    @OnClick(R.id.lca_remind)
    public void onClickRemind(View view) {
        if (TextUtils.isEmpty(mExclamationUrl))
            return;
       /* mPopupTextview.setText(mExclamation);
        mPopupWindow.showAsDropDown(remindIv);*/
        FRLog.e("WANG", "URL" + mExclamationUrl);
        WebViewActivity.start(this, mExclamationUrl);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case MyOwnLoanIncreaseAmountActivity.RESULT_CODE_MYOWNLOANINCREASEAMOUNTACTIVITY_RETURN:
                getLoanData();
                break;
        }
    }
}
